package com.fone.player.storage;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore.Video.Media;

import com.fone.player.entity.MediaFile;
import com.fone.player.entity.MediaFolder;

import de.greenrobot.event.EventBus;

/**
 * 本地文件模块
 * 
 * @author wangyang
 * 
 */
final class FileLocalModule {
	private static Context sContext = null;
	private FileFullScanRunnable mFileFullScanRunnable = null;
	private FileFastScanRunnable mFileFastScanRunnable = null;
	private static final FileLocalModule mInstance = new FileLocalModule();

	static FileLocalModule getInstance() {
		return mInstance;
	}

	/**
	 * 初始化{@link com.fone.player.storage.StorageModule}
	 * 
	 * @param context
	 *            当前上下文
	 */
	static void init(Context context) {

		if (context == null) {
			throw new NullPointerException("activity is null");
		}
		sContext = context;

		FileDataBaseAdapter.init(context);
	}

	/**
	 * 
	 * 扫描外部存储<br>
	 * 异步方法
	 * 
	 * @return void
	 */

	void scanningExternalStorage() {
		if (Build.VERSION.SDK_INT <= 18) {
			IntentFilter intentfilter = new IntentFilter(
					Intent.ACTION_MEDIA_SCANNER_STARTED);
			intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
			intentfilter.addDataScheme("file");
			ScanBroadcastReceiver scanBroadcastReceiver = new ScanBroadcastReceiver();
			sContext.registerReceiver(scanBroadcastReceiver, intentfilter);
			sContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
					.parse("file://"
							+ Environment.getExternalStorageDirectory()
									.getAbsolutePath())));
		} else {

			// fix bug:Android4.4 java.lang.SecurityException: Permission
			// Denial: not allowed to send broadcast
			// android.intent.action.MEDIA_MOUNTED
			scanningExternalStorageByMediaScannerConnection();

		}

	}

	@TargetApi(Build.VERSION_CODES.FROYO)
	void scanningExternalStorageByMediaScannerConnection() {
		// fix bug:Android4.4 java.lang.SecurityException: Permission
		// Denial: not allowed to send broadcast
		// android.intent.action.MEDIA_MOUNTED
		// 开始扫描
		Message message = new Message();
		message.what = StorageModule.MSG_ACTION_MEDIA_SCANNER_STARTED;
		EventBus.getDefault().post(message);

		MediaScannerConnection.scanFile(sContext, new String[] { Environment
				.getExternalStorageDirectory().getAbsolutePath() }, null,
				new OnScanCompletedListener() {

					@Override
					public void onScanCompleted(String path, Uri uri) {
						// 扫描完成
						Message message = new Message();
						message.what = StorageModule.MSG_ACTION_MEDIA_SCANNER_FINISHED;
						EventBus.getDefault().post(message);
					}
				});
	}

	/**
	 * 
	 * 扫描媒体库<br>
	 * 异步方法
	 * 
	 * @return void
	 */
	void scanningMediaStore() {

		// 开启任务
		mFileFastScanRunnable = new FileFastScanRunnable(sContext);
		StorageThreadPoolManager.getInstance().addTask(mFileFastScanRunnable);

	}

	/**
	 * 
	 * 扫描所有存储器<br>
	 * 异步方法
	 * 
	 * @param eventBus
	 *            消息传递
	 * @return void
	 */
	void scanningAllStorage() {
		// 开启任务
		mFileFullScanRunnable = new FileFullScanRunnable(sContext);
		StorageThreadPoolManager.getInstance().addTask(mFileFullScanRunnable);
	}

	/**
	 * 
	 * 取消扫描(只支持全盘扫描,不包括系统自动扫描)<br>
	 * 异步方法
	 * 
	 * @param eventBus
	 *            消息传递
	 * @return void
	 */
	void cancelScanning() {

		if (mFileFullScanRunnable != null) {
			mFileFullScanRunnable.cancel();
		}
		if (mFileFastScanRunnable != null) {
			mFileFastScanRunnable.cancel();
		}
	}

	/**
	 * 
	 * 根据媒体库获取视频文件集合
	 * 
	 * @param eventBus
	 *            消息传递
	 * @return ArrayList<MediaFile>
	 */
	void getVideoFileList(final int listType) {

		switch (listType) {
		case StorageModule.LIST_TYPE_FILE_NORMAL_VIDEO:
			// 文件列表
			new Thread(new Runnable() {

				@Override
				public void run() {
					Message message = new Message();
					Bundle bundle = new Bundle();
					ArrayList<MediaFile> normalMediaFileList = FileDataBaseAdapter
							.getInstance().getFileList(listType);
					message.what = StorageModule.MSG_NORMAL_FILE_LIST_SUCCESS;
					bundle.putParcelableArrayList(MediaFile.MEDIA_FILE_LIST,
							normalMediaFileList);
					message.setData(bundle);
					EventBus.getDefault().post(message);
				}
			}).start();

			break;
		case StorageModule.LIST_TYPE_FILE_ENCRYPT_VIDEO:
			// 文件列表
			new Thread(new Runnable() {

				@Override
				public void run() {
					Message message = new Message();
					Bundle bundle = new Bundle();
					ArrayList<MediaFile> encryptMediaFileList = FileDataBaseAdapter
							.getInstance().getFileList(listType);
					message.what = StorageModule.MSG_ENCRYPT_FILE_LIST_SUCCESS;
					bundle.putParcelableArrayList(MediaFile.MEDIA_FILE_LIST,
							encryptMediaFileList);
					message.setData(bundle);
					EventBus.getDefault().post(message);
				}
			}).start();

			break;
		default:
			throw new IllegalArgumentException(
					"FileModule.getVideoList(EventBus eventBus, int listType) listType is IllegalArgument,Please re assignment!");
		}

	}

	/**
	 * 
	 * 获取视频文件夹集合
	 * 
	 * @return ArrayList<MediaFolder>
	 */
	void getVideoFolderList() {
		ArrayList<MediaFolder> mediaFolderList = FileDataBaseAdapter
				.getInstance().getFolderList();
		Message message = new Message();
		Bundle bundle = new Bundle();
		message.what = StorageModule.MSG_NORMAL_FOLDER_LIST_SUCCESS;
		bundle.putParcelableArrayList(MediaFolder.MEDIA_FOLDER_LIST,
				mediaFolderList);
		message.setData(bundle);
		EventBus.getDefault().post(message);
	}

	/**
	 * 
	 * 根据文件夹路径返回文件集合
	 * 
	 * @param mediaFolderList
	 * @param folderPath
	 *            文件夹路径
	 * @return void
	 * @throws
	 */
	void getVideoFileListByFolderPath(String folderPath) {
		ArrayList<MediaFile> mediaFileList = FileDataBaseAdapter.getInstance()
				.getFileList(folderPath);
		Message message = new Message();
		Bundle bundle = new Bundle();
		message.what = StorageModule.MSG_FOLDER_FILE_LIST_SUCCESS;
		bundle.putParcelableArrayList(MediaFile.MEDIA_FILE_LIST, mediaFileList);
		message.setData(bundle);
		EventBus.getDefault().post(message);

	}

	/**
	 * 
	 * 根据文件路径删除文件 <br>
	 * 同步方法
	 * 
	 * @param filePath
	 *            文件路径
	 * @return int 操作结果<br>
	 *         1 成功<br>
	 *         -1 删除媒体库记录失败<br>
	 *         -2 删除异常<br>
	 */
	int deleteFileByFilePath(String filePath) {
		return FileDataBaseAdapter.getInstance().deleteFileByFilePath(filePath);
	}

	/**
	 * 
	 * 更新加密状态
	 * 
	 * @param id
	 *            文件ID
	 * @param isEncrypt
	 *            加密状态
	 * @return void
	 */
	int updateEncryptFile(long id, boolean isEncrypt) {
		return FileDataBaseAdapter.getInstance().updateEncryptState(id,
				isEncrypt);
	}

	int getFileCount() {
		return FileDataBaseAdapter.getInstance().getFileCount();
	}

	/**
	 * 根据URI返回文件路径
	 * 
	 * @param uri
	 *            文件URI
	 * @return String 文件路径
	 */
	String getFilePathByMediaUri(String uri) {
		String path = null;
		Cursor cursor = sContext.getContentResolver().query(Uri.parse(uri),
				null, null, null, null);
		if (cursor.moveToFirst()) {
			path = cursor.getString(cursor.getColumnIndex(Media.DATA));
		}
		cursor.close();
		return path;
	}
}
